package com.cy.dda.service.comm.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.utils.JsonObjectMapper;
import com.cy.dda.comm.utils.SpringELUtils;
import com.cy.dda.dao.mongodb.SmsRecordDao;
import com.cy.dda.model.Result;
import com.cy.dda.model.doc.SmsRecord;
import com.cy.dda.model.enums.SmsType;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.comm.SmsService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import java.util.Date;
import java.util.Map;

/**
 * @description: 阿里云短信服务
 * @author: Ocean
 * @create: 2018-07-24 18:57
 **/
@Service
@Slf4j
public class AliyunSmsServiceImpl extends BaseService implements SmsService {

	@Autowired
    private SmsRecordDao smsRecordDao;
	
    @Value("${aliyun.sms.secret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.key}")
    private String accessKeyId;
    private final String sign = "超越惠升";
    //短信API产品名称（短信产品名固定，无需修改）
    private final String product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    private final String domain = "dysmsapi.aliyuncs.com";
    private IAcsClient acsClient;

    @PostConstruct
    public void initBean() {
        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        try {
            DefaultProfile.addEndpoint("cn-shenzhen", "cn-shenzhen", product, domain);
        } catch (ClientException e) {
            log.error("initBean error:", e);
        }
        IClientProfile profile = DefaultProfile.getProfile("cn-shenzhen", accessKeyId,
                accessKeySecret);
        acsClient = new DefaultAcsClient(profile);
    }


    @Override
    public Result send(String mobile, SmsType type, Map<String, Object> params) {

    	//封装短信发送内容
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(mobile);
        request.setSignName(sign);
        request.setTemplateCode(type.getId());
        String json = JsonObjectMapper.toJson(params);
        request.setTemplateParam(json);
        log.info("sms send to [{}], params [{}]", mobile, json);

        //记录短信
        String context = SpringELUtils.getValue(type.getContext(), params);
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setMobile(mobile);
        smsRecord.setType(type);
        smsRecord.setContext(context);
        smsRecord.setCreateTime(new Date());
        
        if (!Constants.IS_PROD) {
            log.info("非prod环境不发送真实短信");
            smsRecord.setStatus("SUCCESS");
            smsRecordDao.insert(smsRecord);
            return Result.success("发生成功");
        }
        
        //发送短信返回
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("acsClient.getAcsResponse(request) error:", e);
            smsRecord.setStatus("EXCEPTION");
            smsRecordDao.insert(smsRecord);
            return Result.fail("系统异常");
        }

        Result result = new Result();

        if(sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
            result.setOk(true);
            result.setMessage("发生成功");
            smsRecord.setStatus("SUCCESS");
        } else {
        	result.setMessage("发生失败");
        	smsRecord.setStatus("FAIL");
        }
        
        smsRecordDao.insert(smsRecord);
        //发送请求成功
        return result;
    }

}
